package com.foodorder.service;

import com.foodorder.entity.Admin;
import com.foodorder.entity.Order;
import com.foodorder.entity.Store;
import com.foodorder.entity.User;
import com.foodorder.repository.AdminRepository;
import com.foodorder.repository.OrderRepository;
import com.foodorder.repository.StoreRepository;
import com.foodorder.repository.UserRepository;
import com.foodorder.repository.ProductRepository;
import com.foodorder.repository.ReviewRepository;
import com.foodorder.repository.CouponRepository;
import com.foodorder.dto.LoginRequest;
import com.foodorder.dto.LoginResponse;
import com.foodorder.utils.JwtUtils;
import com.foodorder.exception.AccountDisabledException;
import com.foodorder.exception.InvalidCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理员服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminService {
    
    private final UserRepository userRepository;
    private final StoreRepository storeRepository;
    private final OrderRepository orderRepository;
    private final ProductRepository productRepository;
    private final ReviewRepository reviewRepository;
    private final CouponRepository couponRepository;
    private final AdminRepository adminRepository;
    private final JwtUtils jwtUtils;
    private final PasswordEncoder passwordEncoder;
    
    /**
     * 测试数据库连接和管理员数据
     */
    public Map<String, Object> testDatabase() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查管理员表是否存在数据
            long adminCount = adminRepository.count();
            result.put("adminCount", adminCount);
            
            // 获取所有管理员用户名
            List<String> adminUsernames = adminRepository.findAll().stream()
                .map(Admin::getUsername)
                .collect(Collectors.toList());
            result.put("adminUsernames", adminUsernames);
            
            // 检查是否存在admin用户
            boolean adminExists = adminRepository.findByUsername("admin").isPresent();
            result.put("adminUserExists", adminExists);
            
            result.put("status", "success");
        } catch (Exception e) {
            result.put("status", "error");
            result.put("error", e.getMessage());
        }
        return result;
    }
    
    /**
     * 管理员登录
     */
    public LoginResponse adminLogin(LoginRequest request) {
        // 根据用户名查找管理员
        String username = request.getUsername() != null ? request.getUsername() : request.getEmail();
        Admin admin = adminRepository.findByUsername(username)
                .orElseThrow(() -> {
                    log.warn("Attempted login with non-existent admin username: {}", username);
                    return new InvalidCredentialsException("管理员不存在或密码错误");
                });
        
        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), admin.getPassword())) {
            log.warn("Incorrect password attempt for admin: {}", username);
            throw new InvalidCredentialsException("管理员不存在或密码错误");
        }
        
        // 检查账号状态
        if (admin.getStatus() != Admin.AdminStatus.ACTIVE) {
            log.warn("Attempted login by disabled admin account: {}", username);
            throw new AccountDisabledException("账号已被禁用");
        }
        
        // 生成JWT Token
        String token = jwtUtils.generateToken(
            admin.getId(), 
            admin.getUsername(), 
            "ADMIN"
        );
        
        // 更新最后登录时间
        admin.setLastLoginTime(LocalDateTime.now());
        adminRepository.save(admin);
        
        log.info("Admin {} logged in successfully", username);
        return LoginResponse.builder()
                .token(token)
                .user(admin)
                .build();
    }
    
    /**
     * 获取系统统计数据
     */
    public Map<String, Object> getSystemStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 基础统计
        stats.put("totalUsers", userRepository.count());
        stats.put("totalStores", storeRepository.count());
        stats.put("totalOrders", orderRepository.count());
        stats.put("totalProducts", productRepository.count());
        stats.put("totalReviews", reviewRepository.count());
        stats.put("totalCoupons", couponRepository.count());
        
        // 今日统计
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        stats.put("todayOrders", orderRepository.countByCreatedAtAfter(today));
        stats.put("todayUsers", userRepository.countByCreatedAtAfter(today));
        
        // 系统状态
        stats.put("systemStatus", "运行正常");
        stats.put("lastUpdateTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return stats;
    }
    
    /**
     * 获取店铺销量统计
     */
    public Map<String, Object> getStoreSalesStatistics() {
        Map<String, Object> salesData = new HashMap<>();
        
        // 店铺销量排行
        List<Map<String, Object>> topStores = new ArrayList<>();
        storeRepository.findAll().forEach(store -> {
            Map<String, Object> storeData = new HashMap<>();
            storeData.put("id", store.getId());
            storeData.put("name", store.getName());
            storeData.put("monthlySales", store.getMonthlySales());
            storeData.put("rating", store.getRating());
            // 计算评论数量
            long reviewCount = reviewRepository.countByStoreId(store.getId());
            storeData.put("reviewCount", reviewCount);
            
            // 计算总收入
            BigDecimal totalRevenue = orderRepository.findByStoreId(store.getId())
                    .stream()
                    .map(order -> order.getTotalAmount())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            storeData.put("totalRevenue", totalRevenue);
            
            topStores.add(storeData);
        });
        
        // 按销量排序
        topStores.sort((a, b) -> Integer.compare(
                (Integer) b.get("monthlySales"), 
                (Integer) a.get("monthlySales")
        ));
        
        salesData.put("topStores", topStores);
        salesData.put("totalStores", topStores.size());
        
        return salesData;
    }
    
    /**
     * 获取用户统计数据
     */
    public Map<String, Object> getUserStatistics() {
        Map<String, Object> userStats = new HashMap<>();
        
        long totalUsers = userRepository.count();
        long activeUsers = userRepository.countByStatus(com.foodorder.entity.User.UserStatus.ACTIVE);
        
        userStats.put("totalUsers", totalUsers);
        userStats.put("activeUsers", activeUsers);
        userStats.put("inactiveUsers", totalUsers - activeUsers);
        userStats.put("userGrowthRate", calculateUserGrowthRate());
        
        // 用户注册趋势（最近7天）
        List<Map<String, Object>> registrationTrend = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            LocalDateTime date = LocalDateTime.now().minusDays(i).withHour(0).withMinute(0).withSecond(0);
            LocalDateTime nextDate = date.plusDays(1);
            
            long count = userRepository.countByCreatedAtBetween(date, nextDate);
            
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", date.format(DateTimeFormatter.ofPattern("MM-dd")));
            dayData.put("count", count);
            registrationTrend.add(dayData);
        }
        
        userStats.put("registrationTrend", registrationTrend);
        
        return userStats;
    }
    
    /**
     * 获取订单统计数据
     */
    public Map<String, Object> getOrderStatistics() {
        Map<String, Object> orderStats = new HashMap<>();
        
        long totalOrders = orderRepository.count();
        orderStats.put("totalOrders", totalOrders);
        
        // 按状态统计
        Arrays.stream(com.foodorder.entity.Order.OrderStatus.values()).forEach(status -> {
            long count = orderRepository.countByStatus(status);
            orderStats.put(status.name().toLowerCase() + "Orders", count);
        });
        
        // 按类型统计
        long deliveryOrders = orderRepository.countByType(com.foodorder.entity.Order.OrderType.DELIVERY);
        long dineInOrders = orderRepository.countByType(com.foodorder.entity.Order.OrderType.DINE_IN);
        
        orderStats.put("deliveryOrders", deliveryOrders);
        orderStats.put("dineInOrders", dineInOrders);
        
        // 订单趋势（最近7天）
        List<Map<String, Object>> orderTrend = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            LocalDateTime date = LocalDateTime.now().minusDays(i).withHour(0).withMinute(0).withSecond(0);
            LocalDateTime nextDate = date.plusDays(1);
            
            long count = orderRepository.countByCreatedAtBetween(date, nextDate);
            
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", date.format(DateTimeFormatter.ofPattern("MM-dd")));
            dayData.put("count", count);
            orderTrend.add(dayData);
        }
        
        orderStats.put("orderTrend", orderTrend);
        
        return orderStats;
    }
    
    /**
     * 获取收入统计数据
     */
    public Map<String, Object> getRevenueStatistics() {
        Map<String, Object> revenueStats = new HashMap<>();
        
        // 总收入
        BigDecimal totalRevenue = orderRepository.findAll()
                .stream()
                .map(order -> order.getTotalAmount())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        revenueStats.put("totalRevenue", totalRevenue);
        
        // 今日收入
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        BigDecimal todayRevenue = orderRepository.findByCreatedAtAfter(today)
                .stream()
                .map(order -> order.getTotalAmount())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        revenueStats.put("todayRevenue", todayRevenue);
        
        // 平均订单金额
        BigDecimal avgOrderAmount = totalRevenue.divide(
                BigDecimal.valueOf(Math.max(orderRepository.count(), 1)), 
                2, 
                BigDecimal.ROUND_HALF_UP
        );
        revenueStats.put("avgOrderAmount", avgOrderAmount);
        
        // 收入趋势（最近7天）
        List<Map<String, Object>> revenueTrend = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            LocalDateTime date = LocalDateTime.now().minusDays(i).withHour(0).withMinute(0).withSecond(0);
            LocalDateTime nextDate = date.plusDays(1);
            
            BigDecimal dayRevenue = orderRepository.findByCreatedAtBetween(date, nextDate)
                    .stream()
                    .map(order -> order.getTotalAmount())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", date.format(DateTimeFormatter.ofPattern("MM-dd")));
            dayData.put("revenue", dayRevenue);
            revenueTrend.add(dayData);
        }
        
        revenueStats.put("revenueTrend", revenueTrend);
        
        return revenueStats;
    }
    
    /**
     * 导出数据
     */
    public String exportData(String type) {
        try {
            switch (type.toLowerCase()) {
                case "users":
                    return exportUsers();
                case "stores":
                    return exportStores();
                case "orders":
                    return exportOrders();
                case "products":
                    return exportProducts();
                default:
                    return "不支持的导出类型: " + type;
            }
        } catch (Exception e) {
            log.error("导出数据失败: {}", e.getMessage());
            return "导出失败: " + e.getMessage();
        }
    }
    
    /**
     * 导入数据
     */
    public String importData(String type, String data) {
        try {
            switch (type.toLowerCase()) {
                case "users":
                    return importUsers(data);
                case "stores":
                    return importStores(data);
                case "orders":
                    return importOrders(data);
                case "products":
                    return importProducts(data);
                default:
                    return "不支持的导入类型: " + type;
            }
        } catch (Exception e) {
            log.error("导入数据失败: {}", e.getMessage());
            return "导入失败: " + e.getMessage();
        }
    }
    
    // 私有辅助方法
    private double calculateUserGrowthRate() {
        LocalDateTime lastMonth = LocalDateTime.now().minusMonths(1);
        long lastMonthUsers = userRepository.countByCreatedAtBefore(lastMonth);
        long totalUsers = userRepository.count();
        
        if (lastMonthUsers == 0) return 100.0;
        return ((double) (totalUsers - lastMonthUsers) / lastMonthUsers) * 100;
    }
    
    private String exportUsers() {
        StringBuilder csv = new StringBuilder();
        csv.append("ID,邮箱,昵称,手机号,状态,创建时间\n");
        
        userRepository.findAll().forEach(user -> {
            csv.append(user.getId()).append(",")
               .append(user.getEmail()).append(",")
               .append(user.getNickname()).append(",")
               .append(user.getPhone()).append(",")
               .append(user.getStatus()).append(",")
               .append(user.getCreatedAt()).append("\n");
        });
        
        return csv.toString();
    }
    
    private String exportStores() {
        StringBuilder csv = new StringBuilder();
        csv.append("ID,店铺名称,地址,月销量,评分,状态,创建时间\n");
        
        storeRepository.findAll().forEach(store -> {
            csv.append(store.getId()).append(",")
               .append(store.getName()).append(",")
               .append(store.getAddress()).append(",")
               .append(store.getMonthlySales()).append(",")
               .append(store.getRating()).append(",")
               .append(store.getBusinessStatus()).append(",")
               .append(store.getCreatedAt()).append("\n");
        });
        
        return csv.toString();
    }
    
    private String exportOrders() {
        StringBuilder csv = new StringBuilder();
        csv.append("ID,订单号,用户ID,店铺ID,类型,状态,总金额,创建时间\n");
        
        orderRepository.findAll().forEach(order -> {
            csv.append(order.getId()).append(",")
               .append(order.getOrderNo()).append(",")
               .append(order.getUserId()).append(",")
               .append(order.getStoreId()).append(",")
               .append(order.getType()).append(",")
               .append(order.getStatus()).append(",")
               .append(order.getTotalAmount()).append(",")
               .append(order.getCreatedAt()).append("\n");
        });
        
        return csv.toString();
    }
    
    private String exportProducts() {
        StringBuilder csv = new StringBuilder();
        csv.append("ID,商品名称,店铺ID,分类ID,价格,库存,月销量,状态,创建时间\n");
        
        productRepository.findAll().forEach(product -> {
            csv.append(product.getId()).append(",")
               .append(product.getName()).append(",")
               .append(product.getStoreId()).append(",")
               .append(product.getCategoryId()).append(",")
               .append(product.getPrice()).append(",")
               .append(product.getStock()).append(",")
               .append(product.getMonthlySales()).append(",")
               .append(product.getStatus()).append(",")
               .append(product.getCreatedAt()).append("\n");
        });
        
        return csv.toString();
    }
    
    private String importUsers(String data) {
        // 简单的CSV导入实现
        String[] lines = data.split("\n");
        int imported = 0;
        
        for (int i = 1; i < lines.length; i++) { // 跳过标题行
            String[] fields = lines[i].split(",");
            if (fields.length >= 6) {
                // 这里可以实现具体的用户导入逻辑
                imported++;
            }
        }
        
        return "成功导入 " + imported + " 个用户";
    }
    
    private String importStores(String data) {
        String[] lines = data.split("\n");
        int imported = 0;
        
        for (int i = 1; i < lines.length; i++) {
            String[] fields = lines[i].split(",");
            if (fields.length >= 7) {
                imported++;
            }
        }
        
        return "成功导入 " + imported + " 个店铺";
    }
    
    private String importOrders(String data) {
        String[] lines = data.split("\n");
        int imported = 0;
        
        for (int i = 1; i < lines.length; i++) {
            String[] fields = lines[i].split(",");
            if (fields.length >= 8) {
                imported++;
            }
        }
        
        return "成功导入 " + imported + " 个订单";
    }
    
    private String importProducts(String data) {
        String[] lines = data.split("\n");
        int imported = 0;
        
        for (int i = 1; i < lines.length; i++) {
            String[] fields = lines[i].split(",");
            if (fields.length >= 9) {
                imported++;
            }
        }
        
        return "成功导入 " + imported + " 个商品";
    }
}